//
//  MJ_SearchViewController.m
//  UEAssistant
//
//  Created by mac on 2018/1/9.
//  Copyright © 2018年 youyixinxi. All rights reserved.
//

#import "MJ_SearchViewController.h"
#import "MJ_SearchTextField.h"
#import <FFDropDownMenu/FFDropDownMenuView.h>
#import <Masonry.h>
#import "MJ_ScreenViewController.h"
#import "MJ_TaskCellLayout.h"
#import "MJ_TaskTableViewCell.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "MJ_OperationViewModel.h"
#import "MJReportListModel.h"
#import "MJ_TaskCellLayout.h"
#import "MJ_ProjectDetailController.h"
@interface MJ_SearchViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource,UITextFieldDelegate>
/**搜索框最底层view*/
@property (strong, nonatomic)UIView *backgroundGrayView;
/**
 选择项目经理/项目名称
 */
@property (strong, nonatomic)MJ_SelectButton *selectBtn;
/**
 选择按钮旁边的竖线
 */
@property (strong, nonatomic)UIView *longLine;
/**
 取消
 */
@property (strong, nonatomic)UIButton *cancelBtn;
/**
 主要输入框
 */
@property (strong, nonatomic)MJ_SearchTextField *searchTextField;
/**
 搜索框下面的分割线
 */
@property (strong, nonatomic)UIView *separtorLine;
/**
 最近使用/历史搜索 label
 */
@property (strong, nonatomic)UILabel *recentlyUsedLabel;
/**
 删除按钮
 */
@property (strong, nonatomic)UIButton *deletButton;

/**
 历史搜索/最近使用下面的分割线
 */
@property (strong, nonatomic)UIView *deletLine;
/**
 筛选按钮
 */
@property (strong, nonatomic)UIButton *screeningButton;
/**
 下拉菜单(项目经理/项目名称)
 */
@property (strong, nonatomic)FFDropDownMenuView *menuView;
/**
 是否显示最近使用
 */
@property (assign, nonatomic)BOOL showHistory;


@property (strong, nonatomic)MJ_OperationViewModel *viewModel;
@property (strong, nonatomic)UITableView *tableView;

@end

@implementation MJ_SearchViewController

#pragma mark --懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 120, Screen_Width, Screen_Height-120) style:UITableViewStylePlain];
        [_tableView registerClass:[MJ_TaskTableViewCell class] forCellReuseIdentifier:@"MJ_TaskTableViewCell"];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = [UIColor colorWithHexString:@"#e0e0e0"];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
    }
    return _tableView;
}
- (UIView *)backgroundGrayView {
    if (!_backgroundGrayView) {
        _backgroundGrayView = [[UIView alloc] initWithFrame:CGRectMake(15, 35, Screen_Width-65, 35)];
        _backgroundGrayView.backgroundColor = lineMainColor;
        _backgroundGrayView.layer.cornerRadius = 5;
        _backgroundGrayView.layer.masksToBounds = YES;
    }
    return _backgroundGrayView;
}
- (MJ_SelectButton *)selectBtn {
    if (!_selectBtn) {
        _selectBtn = [MJ_SelectButton buttonWithType:UIButtonTypeCustom];
        _selectBtn.frame = CGRectMake(0, 0, 90, 35);
        _selectBtn.backgroundColor = [UIColor redColor];
        _selectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _selectBtn.backgroundColor = lineMainColor;
        [_selectBtn setTitle:@"项目经理" forState:UIControlStateNormal];
        [_selectBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        UIImage *pullDown = [[UIImage imageNamed:@"下拉-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [_selectBtn setImage:pullDown forState:UIControlStateNormal];
        [_selectBtn addTarget:self action:@selector(selectBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectBtn;
}
- (UIView *)longLine {
    if (!_longLine) {
        _longLine = [[UIView alloc] initWithFrame:CGRectMake(91, 8, 1, 19)];
        _longLine.backgroundColor = [UIColor colorWithHexString:@"#cccccc"];
    }
    return _longLine;
}
- (UIView *)separtorLine {
    if (!_separtorLine) {
        _separtorLine = [[UIView alloc] initWithFrame:CGRectMake(0, 78, Screen_Width, 1)];
        _separtorLine.backgroundColor = lineMainColor;
    }
    return _separtorLine;
}

- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:mainColor forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _cancelBtn.frame = CGRectMake(Screen_Width-50, 35, 50, 35);
        [_cancelBtn addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

- (MJ_SearchTextField *)searchTextField {
    if (!_searchTextField) {
        _searchTextField = [[MJ_SearchTextField alloc] initWithFrame:CGRectMake(98, 0, Screen_Width-91-65, 35)];
        _searchTextField.backgroundColor = [UIColor clearColor];
        _searchTextField.placeholder = @"搜索";
        _searchTextField.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Nav Bar_搜索"]];
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
        _searchTextField.font = [UIFont systemFontOfSize:14];
        _searchTextField.clearButtonMode = UITextFieldViewModeAlways;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.delegate = self;
    }
    return _searchTextField;
}

- (UILabel *)recentlyUsedLabel {
    if (!_recentlyUsedLabel) {
        _recentlyUsedLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 96, 100, 13)];
        _recentlyUsedLabel.text = @"最近使用";
        _recentlyUsedLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        _recentlyUsedLabel.font = [UIFont systemFontOfSize:13];
    }
    return _recentlyUsedLabel;
}

- (UIButton *)deletButton {
    if (!_deletButton) {
        _deletButton = [UIButton buttonWithType: UIButtonTypeCustom];
        [_deletButton setImage:[UIImage imageNamed:@"删除-1"] forState:UIControlStateNormal];
        _deletButton.frame = CGRectMake(Screen_Width-18-30, 81, 40, 40);
    }
    return _deletButton;
}

//- (UIButton *)screeningButton {
//    if (!_screeningButton) {
//        _screeningButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_screeningButton setTitle:@"筛选" forState:UIControlStateNormal];
//        [_screeningButton setImage:[UIImage imageNamed:@"筛选"] forState:UIControlStateNormal];
//        [_screeningButton setBackgroundImage:[UIImage imageNamed:@"BG"] forState:UIControlStateNormal];
//        _screeningButton.titleLabel.font = [UIFont systemFontOfSize:13];
//        _screeningButton.layer.cornerRadius = 20.0;
//        _screeningButton.layer.masksToBounds = YES;
//        _screeningButton.titleEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0);
//        _screeningButton.imageEdgeInsets = UIEdgeInsetsMake(0, 55, 0, 0);
//        [_screeningButton setTitleColor:mainColor forState:UIControlStateNormal];
//        [_screeningButton addTarget:self action:@selector(screenButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
//
//    }
//    return _screeningButton;
//}
- (MJ_OperationViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[MJ_OperationViewModel alloc] init];
    }
    return _viewModel;
}
#pragma mark --核心代码

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupUI];
}

- (void)loadData {
    _showHistory = YES;
}

- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backgroundGrayView];
    [self.view addSubview:self.cancelBtn];
    [self.view addSubview:self.separtorLine];
    [self.view addSubview:self.recentlyUsedLabel];
    [self.view addSubview:self.deletButton];
    [self.backgroundGrayView addSubview:self.selectBtn];
    [self.backgroundGrayView addSubview:self.longLine];
    [self.backgroundGrayView addSubview:self.searchTextField];
    [self.view addSubview:self.tableView];
    
    
    NSArray *menuModelsArr = [self getDropDownMenuModelsArray];
    self.menuView = [[FFDropDownMenuView alloc] init];
    self.menuView.menuModelsArray = menuModelsArr;
    self.menuView.cellClassName = FFDefaultCell;
    self.menuView.menuWidth = 100;
    self.menuView.iconSize = CGSizeZero;
    self.menuView.menuItemBackgroundColor = FFColor(0, 0, 0, 0.71);
    self.menuView.triangleColor = FFColor(0, 0, 0, 0.71);
    self.menuView.titleColor = [UIColor whiteColor];
    self.menuView.titleFontSize = 14;
    self.menuView.triangleRightMargin = Screen_Width-50;
    self.menuView.menuRightMargin = Screen_Width-15-100;
    self.menuView.menuAnimateType = FFDropDownMenuViewAnimateType_FallFromTop;
    [self.menuView setup];
    
    [self.searchTextField addTarget:self action:@selector(searchEditingChanged:) forControlEvents:UIControlEventEditingChanged];


}

#pragma mark --UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_showHistory) {
        NSArray *arr = [UserDefaults objectForKey:@"searchHistory"] == nil ? @[] :[UserDefaults objectForKey:@"searchHistory"];
        return arr.count;
    }
    return self.viewModel.searchProjectList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_showHistory) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UITableViewCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.separatorInset =UIEdgeInsetsMake(0, 15, 0, 15);
        NSArray *arr = [UserDefaults objectForKey:@"searchHistory"] == nil ? @[] :[UserDefaults objectForKey:@"searchHistory"];
        NSDictionary *dic = arr[arr.count-1-indexPath.row];
        cell.detailTextLabel.text = dic[@"type"];
        cell.textLabel.text = dic[@"vm_name"];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
        cell.detailTextLabel.textColor = [UIColor colorWithHexString:@"#999999"];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#333333"];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        return cell;
        
    }else{
        MJ_TaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MJ_TaskTableViewCell" forIndexPath:indexPath];
        cell.cellLayout = self.viewModel.searchProjectList[indexPath.row];
        return cell;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_showHistory) {
        return 44;
    }
    MJ_TaskCellLayout *layout = self.viewModel.searchProjectList[indexPath.row];
    return layout.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_showHistory) {
        NSArray *arr = [UserDefaults objectForKey:@"searchHistory"] == nil ? @[] :[UserDefaults objectForKey:@"searchHistory"];
        NSDictionary *dic = arr[indexPath.row];
        if ([dic[@"type"] isEqualToString:@"项目经理"]) {
            [self.selectBtn setTitle:@"项目经理" forState:UIControlStateNormal];
            self.searchTextField.text = dic[@"vm_name"];
            [self loadSearchManagerWithSearchValue:dic[@"vm_name"]];
        }else{
            [self.selectBtn setTitle:@"项目名称" forState:UIControlStateNormal];
            self.searchTextField.text = dic[@"vm_name"];
            [self loadProjectWithName:dic[@"vm_name"]];
        }
        
    }else{
        MJ_ProjectDetailController *detailVc = [[MJ_ProjectDetailController alloc] init];
        MJ_TaskCellLayout *layout = self.viewModel.searchProjectList[indexPath.row];
        detailVc.model = layout.projectModel;
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}
//取消返回上一页
- (void)cancelButtonPressed:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//项目经理/项目名称切换View
- (void)selectBtnPressed:(UIButton *)sender {
    [self.menuView showMenu];
}

/** 获取下拉菜单模型数组 */
- (NSArray *)getDropDownMenuModelsArray {
    __weak typeof(self) wSelf = self;
    //菜单模型0
    FFDropDownMenuModel *menuModel0 = [FFDropDownMenuModel ff_DropDownMenuModelWithMenuItemTitle:@"项目经理" menuItemIconName:@"" menuBlock:^{
        __strong typeof(wSelf) sSelf = wSelf;
        [sSelf.selectBtn setTitle:@"项目经理" forState:UIControlStateNormal];
        if (sSelf.searchTextField.text.length > 0) {
            [sSelf loadSearchManagerWithSearchValue:sSelf.searchTextField.text];
        }

    }];
    //菜单模型1
    FFDropDownMenuModel *menuModel1 = [FFDropDownMenuModel ff_DropDownMenuModelWithMenuItemTitle:@"项目名称" menuItemIconName:@"" menuBlock:^{
        //Do Something
        __strong typeof(wSelf) sSelf = wSelf;
        [sSelf.selectBtn setTitle:@"项目名称" forState:UIControlStateNormal];
        if (sSelf.searchTextField.text.length > 0) {
            [sSelf loadProjectWithName:self.searchTextField.text];
        }
    }];
    
    NSArray *menuModelArr = @[menuModel0, menuModel1];
    
    return menuModelArr;
}

//- (void)screenButtonPressed:(UIButton *)sender {
//
//    MJ_ScreenViewController *vc = [[MJ_ScreenViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
//}
//点击搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    NSString *title = self.selectBtn.titleLabel.text;
    if ([title isEqualToString:@"项目经理"]) {
        [self loadSearchManagerWithSearchValue:textField.text];
    }else{
        [self loadProjectWithName:textField.text];
    }
    
    return YES;
}
//搜索项目经理
- (void)loadSearchManagerWithSearchValue:(NSString *)value {
    __weak typeof(self) wSelf = self;
    BOOL hasManage = NO;
    MJProjectListModel *projectModel = [[MJProjectListModel alloc] init];
    for (MJ_TaskCellLayout *layout in self.projectArray) {
        if ([layout.projectModel.vm_name isEqualToString:value]) {
            hasManage = YES;
            projectModel = layout.projectModel;
        }
    }
    if (hasManage) {
        [LSProgressHUD showLoadingToView:self.navigationController.view];
        [self.viewModel loadProjectWithProjectManager:[NSString stringWithFormat:@"%ld",projectModel.vm_id] success:^(BOOL success) {
            __strong typeof(wSelf) sSelf = wSelf;
            if (success) {
                [sSelf.tableView reloadData];
                //历史数据
                [self saveHistoryWithId:projectModel.vm_id vmName:projectModel.vm_name type:@"项目经理"];

                [self searchEditingChanged:self.searchTextField];
            }
            [LSProgressHUD hideForView:sSelf.navigationController.view];
        }];
    }else{
        //如果没有此项目经理，提示无对应项目经理
        [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"未找到对应的项目经理！" andTitleColor:[UIColor whiteColor] andCancel:YES];
    }
}
//搜索项目名称
- (void)loadProjectWithName:(NSString *)name {
    [LSProgressHUD showLoadingToView:self.navigationController.view];
    __weak typeof(self) wSelf = self;
    [self.viewModel loadProjectWithProjectName:name success:^(BOOL success) {
        __strong typeof(wSelf) sSelf = wSelf;
        if (success) {
            [sSelf.tableView reloadData];
            //统计历史
            [self saveHistoryWithId:0 vmName:name type:@"项目名称"];
            [self searchEditingChanged:self.searchTextField];
        }
        [LSProgressHUD hideForView:sSelf.navigationController.view];

    }];
}

- (void)searchEditingChanged:(UITextField *)textField {
    if (textField.text.length < 1) {
        [self setupUIWithShowHistory];
    }else{
        [self setupUIWithHiddenHistory];
    }
    [self.tableView reloadData];
}



//设置显示历史记录的界面
- (void)setupUIWithShowHistory {
    _showHistory = YES;
    self.tableView.frame = CGRectMake(0, 120, Screen_Width, Screen_Height-120);
    [self.view addSubview:self.recentlyUsedLabel];
    [self.view addSubview:self.deletButton];
}
//设置不显示历史记录的界面
- (void)setupUIWithHiddenHistory {
    _showHistory = NO;
    [self.recentlyUsedLabel removeFromSuperview];
    [self.deletButton removeFromSuperview];
    self.tableView.frame = CGRectMake(0, 79, Screen_Width, Screen_Height-79);
}
//保存历史数据
- (void)saveHistoryWithId:(long)vmId vmName:(NSString *)name type:(NSString *)type {
    NSDictionary *dic = @{@"vm_id":[NSString stringWithFormat:@"%ld",vmId],@"vm_name":name,@"type":type};
    NSArray *arr = [UserDefaults objectForKey:@"searchHistory"] == nil ? @[] :[UserDefaults objectForKey:@"searchHistory"];
    for (NSDictionary *dic in arr) {
        if ([dic[@"vm_name"] isEqualToString:name] && [dic[@"type"] isEqualToString:type]) {
            NSInteger index = [arr indexOfObject:dic];
            NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:arr];
            [mutableArray removeObject:[mutableArray objectAtIndex:index]];
            arr = mutableArray;
        }
    }
    if (name.length > 0) {
        arr = [arr arrayByAddingObject:dic];
    }
    [UserDefaults setObject:arr forKey:@"searchHistory"];
}

#pragma mark --空数据处理
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"任务"];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *text = @"空空如也~";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:16.0f],
                                 NSForegroundColorAttributeName: [UIColor darkGrayColor]};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    
    return YES;
}
@end
